﻿using Sidvall.WorkItemManager.Data;
using System.Threading.Tasks;

namespace Sidvall.WorkItemManager.Workflow.WorkItems
{
    public class ConsoleWorkItemProvider : WorkItemProviderBase
    {
        #region Public Members

        #region ExecuteAsync

        public override async Task<WorkItemResult> ExecuteAsync()
        {
            WorkItemResultType result;

            // Parse this.Context
            DeserializeContext();

            var startInfo = GetStartInfo();
            var launchResult = await Sidvall.SystemContext.Current.LauncherManager.LaunchFileAsync(this.ContextItem.FileName, startInfo).ConfigureAwait(false);
            if (launchResult)
                result = WorkItemResultType.Ok;
            else
                result = WorkItemResultType.Failed;

            // Return result
            return new WorkItemResult(result, string.Empty);
        }

        #endregion
        #region GetSensorsAsync

        public override async Task<SensorCollection> GetSensorsAsync()
        {
            // Parse this.Context
            DeserializeContext();

            var sensors = new SensorCollection();
            sensors.AddRange(this.ContextItem.Sensors);
            if ((!string.IsNullOrWhiteSpace(this.ContextItem.FileName)) && (!string.IsNullOrWhiteSpace(this.ContextItem.SensorProviderCodename)))
            {
                var assembly = await Sidvall.SystemContext.Current.CodeManager.GetAssemblyAsync(this.ContextItem.FileName);
                var sensorProvider = Sidvall.SystemContext.Current.CodeManager.CreateInstance(this.ContextItem.SensorProviderCodename, assembly) as ISensorProvider;
                if (sensorProvider != null)
                {
                    var items = await sensorProvider.GetSensorsAsync().ConfigureAwait(false);
                    sensors.AddRange(items);
                }
            }
            return sensors;
        }

        #endregion

        #endregion
        #region Private Members

        private ConsoleWorkItemContext ContextItem { get; set; }

        #region DeserializeContext

        private void DeserializeContext()
        {
            this.ContextItem = ConsoleWorkItemContext.Deserialize(this.Context);
        }

        #endregion
        #region GetStartInfo

        private Sidvall.SystemEnvironment.LauncherOptions GetStartInfo()
        {
            if (this.ContextItem == null)
                return null;
            var arguments = this.Manager?.WorkItem?.WorkItemId.ToString();
            var item = new Sidvall.SystemEnvironment.LauncherOptions()
            {
                DesiredRemainingView = this.ContextItem.WindowStyle,
            };
            return item;
        }

        #endregion

        #endregion
    }
}
